package com.quectel.sdk.hik8700;

import cn.hutool.crypto.digest.MD5;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.quectel.base.tuple.Tuple2;
import com.quectel.base.tuple.Tuples;
import com.quectel.util.common.JacksonUtils;
import com.quectel.util.ex.CheckErrorException;
import com.quectel.util.http.HttpRestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * 在这里编写说明
 *
 * @author: rananxin
 * @email: ryan.ran@quectel.com
 * @date: 2022-10-19 11:01:00
 */
public class Hik8700Requester {

    private static final Logger logger = LoggerFactory.getLogger(Hik8700Requester.class);


    private final static String CONTENT_TYPE = "application/json";

    private static final Cache<String, String> USER_ID_CACHE =
            CacheBuilder.newBuilder().expireAfterAccess(10, TimeUnit.MINUTES).build();

    /**
     * cache
     * k1 host
     * k2 key
     */
    private static Function<Tuple2<String, String>, String> USER_ID_CACHE_FUNC = (t) ->
            "USER_ID:" + t.getT1() + ":" + t.getT2();

    private static final HttpRestUtils HTTP_REST_UTILS = HttpRestUtils.getTrustSSLInstance();

    private String key;
    private String secret;
    private String host;


    private Hik8700Requester(String key, String secret, String host) {
        this.host = host;
        this.secret = secret;
        this.key = key;
    }


    public static Hik8700Requester getInstance(String appKey, String appSecret, String host) {

        return new Hik8700Requester(appKey, appSecret, host);
    }

    public String post(String path, Map<String, Object> params) {
        if (this.host == null) {
            throw new CheckErrorException("checked host " + this.host + " is null");
        }
        params.put("appkey", key);
        params.put("time", System.currentTimeMillis());
        String token = MD5.create().digestHex(path + JacksonUtils.toJsonString(params) + secret).toUpperCase();
        return HTTP_REST_UTILS.post("http://" + host + path + "?token=" + token, params, null, new TypeReference<String>() {
        }).getRight();
    }

    public String getDefaultUserId() {
        return USER_ID_CACHE.asMap().computeIfAbsent(
                USER_ID_CACHE_FUNC.apply(Tuples.of(host, key)),
                (cacheKey) -> {
                    String resp = post("/openapi/service/base/user/getDefaultUserUuid", new HashMap<>());
                    Map<Object, Object> parse = JacksonUtils.parse(resp, HashMap.class);
                    return (String) parse.get("data");
                }
        );
    }

    public static void main(String[] args) {

    }


}
